package com.witmore.skyline.web.service.third.yingshi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.witmore.skyline.web.service.third.yingshi.dto.YSApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Description: YSApiClient 第三方接口调用
 * Author: 豆子高
 * Date: 2025/3/17
 */
@Slf4j
public class YSApiClient {

    public static String getAccessToken() throws Exception {
        String parameters = "appKey=" + ApiYinShiClientConstant.AK + "&appSecret=" + ApiYinShiClientConstant.SK;
        try {
            String response = httpConnectionHandler(ApiYinShiClientConstant.ACCESS_TOKEN_PATH_URL,
                    ApiYinShiClientConstant.METHOD_POST, parameters, ApiYinShiClientConstant.CT_FORM);
            if (StringUtils.isEmpty(response)) {
                throw new Exception("YS 获取 ACCESS_TOKEN接口调用失败 结果为空");
            }
            YSApiResponse ysApiResponse = JSONObject.parseObject(response, YSApiResponse.class);
            if (ysApiResponse.getCode() == null || !("200").equals(ysApiResponse.getCode()) || ysApiResponse.getData() == null) {
                return null;
            }
            YsTokenCache.YSTokenInfo ysTokenInfo = JSONObject.toJavaObject((JSON) ysApiResponse.getData(), YsTokenCache.YSTokenInfo.class);
            return ysTokenInfo.getAccessToken();
        } catch (Exception e) {
            log.error("YS ACCESS_TOKEN GET failed.", e);
            throw new Exception("YS 获取 ACCESS_TOKEN接口调用失败", e);
        }
    }

    public static YSApiResponse getDeviceCapture(String cameraSn) throws Exception {
        String parameters = "accessToken=" + YsTokenCache.getToken() +
                "&deviceSerial=" + cameraSn + "&channelNo=1&quality=1";
        try {
            String response = httpConnectionHandler(ApiYinShiClientConstant.DEVICE_CAPTURE_URL,
                    ApiYinShiClientConstant.METHOD_POST, parameters, ApiYinShiClientConstant.CT_FORM);
            if (StringUtils.isEmpty(response)) {
                throw new Exception("YS 获取 getDeviceCapture 接口调用失败 结果为空");
            }
            return JSONObject.parseObject(response, YSApiResponse.class);
        } catch (Exception e) {
            log.error("YS DEVICE_CAPTURE GET failed.", e);
            throw new Exception("YS 获取 DEVICE_CAPTURE接口调用失败", e);
        }
    }

    /**
     * 接口调用工具
     *
     * @param urlString
     * @param method
     */
    public static String httpConnectionHandler(String urlString, String method, String parameters, String contentType) {
        try {
            // 创建 URL 对象
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方式为
            connection.setRequestMethod(method);

            // 允许输出
            connection.setDoOutput(true);

            // 设置请求头
            connection.setRequestProperty("Content-Type", contentType);

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = parameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 设置连接超时时间和读取超时时间
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 打印响应结果
                String responseStr = response.toString();
                log.info("Response:{}", responseStr);
                return responseStr;
            } else {
                log.warn("GET request failed.");
            }
        } catch (IOException e) {
            log.error("GET request failed.", e);
        }
        return null;
    }


}
